package com.lepu.app.fun.my;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.app.config.UserConfig;
import com.app.utils.Const;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.widget.MyDialog;
import com.lepu.app.fun.my.adapter.AdapterMyMassege;
import com.lepu.app.fun.my.bean.BeanMsgSystem;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.pasm.R;

public class MyMassegeDetailActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener, AsyncRequest {
	private static final String REQUEST_MSG = "request_msg";
	
	private ListView mListView = null;
	private int mType = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_massege_detail_activity);

		init();
	}

	@Override
	public void onResume() {
		super.onResume();

		if(mType == 3){
			UmengHelper.onResume(this, UmengEvent.page_xiaoxi_peizhenfuwu);
		}else if(mType == 4){
			UmengHelper.onResume(this, UmengEvent.page_xiaoxi_zhuanzhenfuwu);
		}

	}

	@Override
	public void onPause() {
		super.onPause();

		if(mType == 3){
			UmengHelper.onPause(this, UmengEvent.page_xiaoxi_peizhenfuwu);
		}else if(mType == 4){
			UmengHelper.onPause(this, UmengEvent.page_xiaoxi_zhuanzhenfuwu);
		}

	}

	@Override
	public void onDestroy() {

		BeanMsgSystem.updateNewMessageRead(LoginUtil.getUserId(),mType);
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@Override
	public void onTopbarRightButtonSelected() {
		cleanData();
	}
	
	private void showHideNoDataLayout(boolean isShow)
	{
		LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
		if(noDataLayout != null)
		{
			if(isShow)
			{
				noDataLayout.setVisibility(View.VISIBLE);
				mListView.setVisibility(View.GONE);
			}else{
				noDataLayout.setVisibility(View.GONE);
				mListView.setVisibility(View.VISIBLE);
			}
		}
	}
	
	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setRightText("清空");
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setOnTopbarNewRightButtonListener(this);
		
		mListView = (ListView) findViewById(R.id.dataListView);
		
		mType = getIntent().getIntExtra("type", 0);
		if(mType == 1){
			topbar.setTopbarTitle("系统通知");
		}else if(mType == 2){
			topbar.setTopbarTitle("新的粉丝");
		}else if(mType == 3){
			topbar.setTopbarTitle("陪诊服务");
		}else if(mType == 4){
			topbar.setTopbarTitle("转诊服务");
		}
		
		refreshView();
		
		requestAlarm();
	}
	
	private void cleanData(){
		String msg = "";
		if(mType == 1){
			msg = "您确定清空消息列表";
		}else if(mType == 2){
			msg = "您确定清空粉丝列表";
		}else if(mType == 3){
			msg = "您确定清空陪诊服务列表";
		}else if(mType == 4){
			msg = "您确定清空转诊服务列表";
		}
		new MyDialog(MyMassegeDetailActivity.this)
		.setMessage(msg)
		.setNegativeButton(R.string.app_cancel,
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {

					}
				})
		.setPositiveButton(R.string.app_ok,
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						BeanMsgSystem.deleteAllItem(LoginUtil.getUserId(), String.valueOf(mType));
						refreshView();
					}
				}).create(null).show();

	}

	/**
	 * 请求消息
	 */
	private void requestAlarm() {

		//系统消息没有登录，不请求
		if(mType == 1 && !LoginUtil.checkIsLogin()){
			return;
		}

		String maxMessageID = "-1";
		String key = Const.CONFIG_MESSAGE_ID+"_"+mType;

		String value = UserConfig.getConfigString(this, key, "");
		if(!TextUtils.isEmpty(value)){
			maxMessageID = value;
		}

		String url = Setting.getMassegeListUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
		    params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			params.put("MessageID", maxMessageID);
			params.put("MessageType", mType);
		} catch (Exception e) {

		}
		map.put("ht", params);
		ApiClient.http_post_main(url, map, null, this, REQUEST_MSG, true, false);
	}

	@Override
	public void RequestComplete(Object arg0, Object data) {
		//解析数据
		ArrayList<BeanMsgSystem> dataArraylist = BeanMsgSystem.parseJsonData((String) data,String.valueOf(mType));
		if(dataArraylist != null && dataArraylist.size() > 0)
		{
			//插入数据库
			for(int i=0; i<dataArraylist.size(); i++){

				BeanMsgSystem item = dataArraylist.get(i);

				item.type = mType+"";
				item.isRead = 0;
				item.userId = LoginUtil.getUserId();

				if(!BeanMsgSystem.getMsgIsExist(item.userId, mType, item.messageId)){
					BeanMsgSystem.insertMyMessage(item);
				}

				String key = Const.CONFIG_MESSAGE_ID+"_"+mType;
				UserConfig.setConfig(this,key,item.messageId);
			}
		}

		refreshView();
	}

	@Override
	public void RequestError(Object arg0, int arg1, String arg2) {
	}
	
	private void refreshView(){
		if(LoginUtil.checkIsLogin()){
			ArrayList<BeanMsgSystem> arrayList = BeanMsgSystem.getMyMessage("", String.valueOf(mType));
			if(arrayList != null && arrayList.size() > 0){
				String userId = LoginUtil.getUserId();

				for(int i=0; i<arrayList.size(); i++){
					BeanMsgSystem item = arrayList.get(i);
					if(!BeanMsgSystem.getMsgIsExist(userId, mType, item.messageId)){
						item.userId = userId;
						BeanMsgSystem.insertMyMessage(item);
					}
				}
			}
		}

		ArrayList<BeanMsgSystem> list = BeanMsgSystem.getMyMessage(LoginUtil.getUserId(), String.valueOf(mType));
		if(list == null || list.size() == 0){
			showHideNoDataLayout(true);
			return;
		}else{
			showHideNoDataLayout(false);
			AdapterMyMassege adapter = new AdapterMyMassege(MyMassegeDetailActivity.this, list, mType);
			mListView.setAdapter(adapter);
		}
			
	}

}
